package models

import (
	"errors"
	"github.com/liangchao/blogo/src/common/global"
	"time"
)

type Blog struct {
	BlogId           int      `json:"blog_id" gorm:"primaryKey"`
	BlogTitle        string   `json:"blog_title"`
	BlogSubUrl       string   `json:"blog_sub_url"`
	BlogCoverImage   string   `json:"blog_cover_image"`
	BlogSummary      string   `json:"blog_summary"`
	BlogContent      string   `json:"blog_content" gorm:"-"`
	BlogCategoryId   int      `json:"blog_category_id"`
	BlogCategoryName string   `json:"blog_category_name" gorm:"-"`
	BlogTags         []string `json:"blog_tags" grom:"-"`

	BlogStatus    int        `json:"blog_status"`
	BlogStatusStr string     `json:"blog_status_str" gorm:"-"` // 博客状态 1 是已发表 0 是草稿
	BlogViews     int        `json:"blog_views"`
	BlogLikes     int        `json:"blog_likes"`
	AuthorID      int        `json:"author_id" gorm:"-"`
	AuthorName    string     `json:"author_name"`
	EnableComment int        `json:"enable_comment"`
	IsDeleted     int        `json:"is_deleted"`
	CreateTime    *time.Time `json:"create_time"`
	CreateTimeStr string     `json:"create_time_str" gorm:"-"`
	UpdateTime    *time.Time `json:"update_time"`
	UpdateTimeStr string     `json:"update_time_str" gorm:"-"`
}

func (b *Blog) TableName() string {
	return "tb_blog"
}

// GetHotBlog 获取热门的博客
func (b *Blog) GetHotBlog(limit int) (blogs []Blog, err error) {
	err = global.DB.Table(b.TableName()).Where("is_deleted = ? and blog_status = ?", 0, 1).Order("blog_views desc").Limit(limit).Find(&blogs).Error
	return
}

// GetRecentBlogList 获取最近的博客列表
func (b *Blog) GetRecentBlogList(limit int) (blogs []Blog, err error) {
	err = global.DB.Table(b.TableName()).Select("blog_id", "author_name", "blog_title", "blog_summary", "create_time", "blog_sub_url").Where("is_deleted = ? and blog_status = ?", 0, 1).Order("create_time desc").Limit(limit).Find(&blogs).Error
	return
}

// GetBlogById 获取博客通过id
func (b *Blog) GetBlogById() (blog Blog, err error) {
	err = global.DB.Table(b.TableName()).Where("is_deleted = ? and blog_id = ?", 0, b.BlogId).Find(&blog).Error
	return
}

// GetBlogsByTitleKeywords 获得博客通过标题关键字
func (b *Blog) GetBlogsByTitleKeywords(keywords string, offset int, limit int) (blogs []Blog, total int64, err error) {
	err = global.DB.Table(b.TableName()).Where("blog_title like ?", "%"+keywords+"%").Count(&total).Offset(offset).Limit(limit).Find(&blogs).Error
	return
}

// GetBlogsByCategoryKeywords 获得博客通过分类关键字
func (b *Blog) GetBlogsByCategoryKeywords(keywords string, offset int, limit int) (blogs []Blog, total int64, err error) {
	err = global.DB.Table(b.TableName()).Where("blog_category_id in (?)", global.DB.Table("tb_blog_category").Where("category_name like ?", "%"+keywords+"%").Select("category_id")).Count(&total).Offset(offset).Limit(limit).Find(&blogs).Error
	return
}

// GetBlogsByTagKeywords 获得博客通过标签关键字
func (b *Blog) GetBlogsByTagKeywords(keywords string, offset int, limit int) (blogs []Blog, total int64, err error) {
	err = global.DB.Table("tb_blog").Where("blog_id in (?)", global.DB.Table("tb_blog_tag_relation").Where("tag_id in (?)", global.DB.Table("tb_blog_tag").Where("tag_name like (?)", "%"+keywords+"%").Select("tag_id")).Distinct("blog_id").Select("blog_id")).Count(&total).Offset(offset).Limit(limit).Find(&blogs).Error
	return
}

// DeleteByUd 通过id删除博客
func (b *Blog) DeleteById(id int) (err error) {
	err = global.DB.Debug().Table(b.TableName()).Delete(b, id).Error
	return
}

// CreateBlog 创建博客
func (blog *Blog) CreateBlog() (err error) {
	err = global.DB.Debug().Table(blog.TableName()).Create(blog).Error
	return

}

// BlogContent 博客内容
type BlogContent struct {
	BlogContentID int        `gorm:"blog_content_id primaryKey" json:"blog_content_id"`
	BlogId        int        `json:"blog_id"`
	BlogContent   string     `json:"blog_content"`
	IsDeleted     int        `json:"is_deleted"`
	CreateTime    *time.Time `json:"create_time"`
	CreateTimeStr string     `json:"create_time_str" gorm:"-"`
	UpdateTime    *time.Time `json:"update_time"`
	UpdateTimeStr string     `json:"update_time" gorm:"-"`
}

// CreateBlogContent 创建博客内容
func (bc *BlogContent) CreateBlogContent() (err error) {
	err = global.DB.Debug().Table(bc.TableName()).Create(bc).Error
	return
}

// TableName 表名
func (*BlogContent) TableName() string {
	return "tb_blog_content"
}

// GetBlogContentByBid 获得博客的内容通过 bid
func (b *BlogContent) GetBlogContentByBid() (blogContent BlogContent, err error) {
	err = global.DB.Table(b.TableName()).Where("is_deleted = ? and blog_id = ?", 0, b.BlogId).Find(&blogContent).Error
	return
}

// GetBlogByYearMonth 查询同一年同一月创建的博客
func (b *Blog) GetBlogByYearMonth(yearMonth string) (blogs []Blog, err error) {
	err = global.DB.Table(b.TableName()).Where("date_format(create_time, '%Y_%m') = ?", yearMonth).Select("blog_title", "blog_sub_url", "create_time").Order("create_time desc").Find(&blogs).Error
	return
}

// GetCreateOldestCreateTime 查询创建时间最久的博客
func (b *Blog) GetCreateOldestCreateTime() (blog Blog, err error) {
	err = global.DB.Table(b.TableName()).Order("create_time").First(&blog).Error
	return
}

// YearMonthBlog 同年同月的博客
type YearMonthBlog struct {
	BlogId           int      `json:"blog_id" gorm:"primaryKey"`
	BlogTitle        string   `json:"blog_title"`
	BlogSubUrl       string   `json:"blog_sub_url"`
	BlogCoverImage   string   `json:"blog_cover_image"`
	BlogSummary      string   `json:"blog_summary"`
	BlogContent      string   `json:"blog_content"`
	BlogCategoryId   int      `json:"blog_category_id"`
	BlogCategoryName string   `json:"blog_category_name" gorm:"-"`
	BlogTags         []string `json:"blog_tags" grom:"-"`

	BlogStatus    int        `json:"blog_status"`
	BlogStatusStr string     `json:"blog_status_str"` // 博客状态 1 是已发表 0 是草稿
	BlogViews     int        `json:"blog_views"`
	BlogLikes     int        `json:"blog_likes"`
	AuthorID      int        `json:"author_id"`
	AuthorName    string     `json:"author_name" gorm:"-"`
	EnableComment int        `json:"enable_comment"`
	IsDeleted     int        `json:"is_deleted"`
	CreateTime    *time.Time `json:"create_time"`
	CreateTimeStr string     `json:"create_time_str" gorm:"-"`
	UpdateTime    *time.Time `json:"update_time"`
	UpdateTimeStr string     `json:"update_time_str" gorm:"-"`
}

// BlogMigrateByMonth 通过月份博客迁移
func (ymb *YearMonthBlog) BlogMigrateByMonth(yearMonth string) (err error) {
	// 创建表结构
	err = errors.New(global.DB.Set("gorm: table_options", "engine = innodb").Migrator().CreateTable(ymb).Error())
	if err != nil {
		return
	}
	err = errors.New(global.DB.Migrator().RenameTable("year_month_blogs", yearMonth).Error())

	// 迁移数据
	return err
}

// UserBlog 用户博客的联系
type UserBlog struct {
	Id            int        `json:"id" gorm:"relation_id"`
	BlogId        int        `json:"blog_id" gorm:"blog_id"`
	AdminUserId   int        `json:"admin_user_id" gorm:"admin_user_id"`
	CreateTime    *time.Time `json:"create_time" gorm:"create_time"`
	CreateTimeStr string     `json:"create_time_str" gorm:"-"`
}

// TableName 表名
func (*UserBlog) TableName() string {
	return "tb_admin_user_blog_relation"
}

// CreateUserBlog 创建用户博客的联系
func (r *UserBlog) CreateUserBlog() (err error) {
	err = global.DB.Debug().Table(r.TableName()).Create(r).Error
	return
}
